package edu.dublbo.app.generator.controller;

import edu.dublbo.app.generator.advice.exception.OptErrorException;
import edu.dublbo.app.generator.entity.*;
import edu.dublbo.app.generator.result.OptStatus;
import edu.dublbo.app.generator.result.PageResult;
import edu.dublbo.app.generator.result.Result;
import edu.dublbo.app.generator.service.BasicModelDetailService;
import edu.dublbo.app.generator.service.BasicModelService;
import edu.dublbo.app.generator.pojo.MDTypeVo;
import edu.dublbo.app.generator.service.ProjectInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @author habitplus
 * @since 2023/3/5 23:50
 */
@RestController
@RequestMapping("/jsdata")
@Slf4j
public class DataController {

    @Resource
    private BasicModelService modelService;

    @Resource
    private BasicModelDetailService modelDetailService;

    @Resource
    private ProjectInfoService projectService;

    @GetMapping("/model/page")
    public PageResult<TBasicModel> listModePage(@RequestParam(value = "page") int pageNo,
                                                @RequestParam(value = "limit") int pageSize,
                                                @RequestParam(value = "filter", required = false) String searchTxt,
                                                @RequestParam(value = "orderField", required = false) String of,
                                                @RequestParam(value = "orderType", required = false) String ot) {
        return modelService.listPage(pageNo, pageSize, searchTxt, of, ot);
    }

    @PostMapping("/model")
    public Result<Object> addOrModifyModel(@RequestBody TBasicModel model) {
        return modelService.saveOrUpdate(model);
    }

    @DeleteMapping("/model")
    public Result<Object> delModel(@RequestParam String modelId) {
        return modelService.deleteById(modelId);
    }

    @PostMapping("/model/detail")
    public Result<Object> addOrModifyModelDetail(@RequestBody TBasicModelDetail detail) {
        log.error("object is {}", detail.toString());
        return modelDetailService.saveOrUpdate(detail);
    }

    @DeleteMapping("/model/detail")
    public Result<Object> delModelDetail(@RequestParam String modelDetailId) {
        return modelDetailService.delete(modelDetailId);
    }

    @GetMapping("/model/detail/list")
    public Result<List<TBasicModelDetail>> listModelDetail(@RequestParam(value = "modelId") String modelId) {
        List<TBasicModelDetail> list = modelDetailService.list(modelId);
        return Result.<List<TBasicModelDetail>>builder()
                .code(OptStatus.SUCCESS.code)
                .data(list)
                .build();
    }

    @GetMapping("/model/detail/types/list")
    public Result<MDTypeVo> loadModelDetailTypeList() {
        List<TBasicPropertyType> proTypes = modelDetailService.listProTypes();
        List<TBasicColumnType> colTypes = modelDetailService.listColTypes();

        MDTypeVo vo = new MDTypeVo();
        vo.setProTypeList(proTypes);
        vo.setColTypeList(colTypes);

        return Result.<MDTypeVo>builder()
                .code(OptStatus.SUCCESS.code)
                .data(vo)
                .build();
    }

    // 下载源码
    @PostMapping(value = "/project/code/download")
    public ResponseEntity<InputStreamResource> downloadCode(@RequestBody TProjectInfo pf) {
        log.info("request param: {}", pf);

        String filename = pf.getProjectName() + System.currentTimeMillis() + ".zip";
        byte[] bytes = projectService.generateCode(pf);
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", filename));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(bais));

//        OutputStream os = null;
//            try {
        // 配置文件下载
        // 下载文件能正常显示中文

//        log.info("Download  successfully!");
//            } catch (Exception e) {
//                log.error("Download  failed: {}", e.getMessage());
//                throw new OptErrorException(OptStatus.FAIL.code, "文件下载失败");
//            } finally {
//                if (os != null) {
//                    try {
//                        os.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
    }

}


